package com.yy.micro.magic.ext.strategy.format;

import com.yy.micro.magic.core.annotation.Strategy;
import com.yy.micro.magic.core.model.RuntimeMetadata;
import com.yy.micro.magic.core.strategy.RuleStrategyAdapter;
import com.yy.micro.magic.exception.MapException;

import org.springframework.util.StringUtils;

/**
 * 对字符串进行掩码处理，
 * format指定掩码格式：start;end;maskChar，如果没有指定则默认对目标字符串中间四位做掩码，maskChar=*
 *
 */
@Strategy("stringMask")
public class StringMaskStrategy extends RuleStrategyAdapter {
    @Override
    protected void process(final RuntimeMetadata metadata) {
        Object value = metadata.getInputValue();
        if (!StringUtils.isEmpty(value)){
            int start = -1;
            int end = -1;
            String mask = "*";
            String format = metadata.getRule().getFormat();
            if (!StringUtils.isEmpty(format) && format.indexOf(";") >=0){
                String[] fs=format.split(";");
                if (fs.length < 3){
                    throw MapException.create("String mask format wrong "+format);
                }
                if (!StringUtils.isEmpty(fs[0])){
                    start = Integer.parseInt(fs[0]);
                }
                if (!StringUtils.isEmpty(fs[1])){
                    end =Integer.parseInt(fs[1]);
                }
                mask = fs[2];
                if (end < start){
                    throw MapException.create(" string mask format end <= start. "+format);
                }
            }
            addTempResult(metadata.getRule().getName(),format(value.toString(),start,end,mask));
        }
        super.process(metadata);
    }

    private  String format(String value,int start,int end,String mask){
        if (value.length() <=4){
            start = 0;
            end = value.length();
        }
        if (start> value.length()){
            start = -1;
        }
        if (end > value.length()){
            end =-1;
        }
        if (start == -1 || end == -1){
            start = (value.length()-4)/2;
            end = start+4;
        }
        String str = "";
        for (int i=0;i< (end-start);i++){
            str += mask;
        }
        if (start >0 && end <value.length()){
            String s1=value.substring(0,start);
            String s2 = value.substring(end,value.length());
            str =s1+str+s2;
        }
        return  str;
    }
}
